import { getToken, setToken, removeToken } from '@/utils/auth'
import { queryList, deletes, add, update } from '@/api/system/user'
const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
  },

  actions: {
    // 查询
    QueryList({ commit }, datas) {
      // const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        queryList(datas).then(response => {
          const data = response.data
          setToken(data.token)
          commit('SET_TOKEN', data.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    Deletes({ commit }, ids) {
      return new Promise((resolve, reject) => {
        deletes(ids).then(response => {
          const data = response.data
          setToken(data.token)
          commit('SET_TOKEN', data.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    /*
     新增用户
     data object
     */

    Add({ commit }, datas) {
      return new Promise((resolve, reject) => {
        add(datas).then(response => {
          const data = response.data
          setToken(data.token)
          commit('SET_TOKEN', data.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    Update({ commit }, datas) {
      return new Promise((resolve, reject) => {
        update(datas).then(response => {
          const data = response.data
          setToken(data.token)
          commit('SET_TOKEN', data.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }

  }
}

export default user
